import * as THREE from "three";
import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
import { DRACOLoader } from "three/examples/jsm/loaders/DRACOLoader.js";
import { reactive } from "vue";
class Model3D {
  constructor(models) {
    this.models = models;
    this.loadPromises = null;
    this.totalModels = models.length;
    const modelsMap = new Map();
    models.forEach((item) => {
      modelsMap.set(item, 0);
    });
    this.allprogressTotal = modelsMap;
    this.state = reactive({ currentProgress: 0 });
    const loader = new GLTFLoader();
    const dracoLoader = new DRACOLoader();
    dracoLoader.setDecoderPath("/glb/draco/");
    loader.setDRACOLoader(dracoLoader);
    this.Group = new THREE.Group();

    // this.Group.position.set(0, 0, 0);
    // this.Group.name = "全部";
    this.loader = loader;
  }

  loadModel(modelPath) {
    return new Promise((resolve, reject) => {
      let progressTotal = 0;
      const onLoad = (gltf) => {
        gltf.scene.name = modelPath
        resolve(gltf.scene);
      };
      const onProgress = (xhr) => {
        progressTotal = xhr.loaded / xhr.total; // 0.3

        // this.allprogressTotal = progressTotal / 3

        // console.log(`Loading ${modelPath}: ${Math.floor(progressTotal * 100)}%:all${Math.floor(this.allprogressTotal * 100)}%`);
        this.updateProgressBar(modelPath, progressTotal); // 更新进度条
      };
      const onError = (error) => {
        reject(error);
      };
      this.loader.load(`/glb/${modelPath}.glb `, onLoad, onProgress, onError);
      //   return { model: null, progress: progressTotal };
    });
  }

  updateProgressBar(modelPath, progressTotal) {
    this.allprogressTotal.set(modelPath, progressTotal);
    const currentProgress = Array.from(this.allprogressTotal.values()).reduce((acc, promise) => {
      acc += promise / this.totalModels;
      return acc;
    }, 0);
    this.state.currentProgress = currentProgress;
    // console.log("当前进度", currentProgress * 100);
  }

  async loadAllModels() {
    try {
      this.loadPromises = this.models.map((modelPath, index) => {
        return this.loadModel(modelPath).then((model) => {
          this.Group.add(model);
          return model;
        });
      });
      return await Promise.all(this.loadPromises);
    } catch (error) {
      console.error("模型加载出错", error);
    }
  }

//   获取模型
    getObjectByName(path){
        return this.Group.getObjectByName(path);
    }
}

export default Model3D;
